import { app, BrowserWindow, ipcMain } from 'electron'
import path from 'path'
import { fileURLToPath } from 'url'
import fs from 'fs/promises'
import https from 'https'
import http from 'http'
import { createWriteStream } from 'fs'

// 在app ready之前设置环境变量以禁用安全警告
process.env.ELECTRON_DISABLE_SECURITY_WARNINGS = true

const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)

let mainWindow

function createWindow() {
  mainWindow = new BrowserWindow({
    width: 1200,
    height: 800,
    webPreferences: {
      preload: path.join(__dirname, 'preload.cjs'),
      nodeIntegration: false,
      contextIsolation: true,
    },
  })

  // 开发环境加载 Vite 开发服务器
  if (process.env.NODE_ENV !== 'production') {
    mainWindow.loadURL('http://localhost:5173')
    mainWindow.webContents.openDevTools()
  } else {
    // 生产环境加载构建后的文件
    mainWindow.loadFile(path.join(__dirname, '../dist/index.html'))
  }

  mainWindow.on('closed', () => {
    mainWindow = null
  })
}

app.whenReady().then(() => {
  createWindow()

  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) {
      createWindow()
    }
  })
})

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

// 下载图片到指定文件夹
ipcMain.handle('download-images', async (event, imageList) => {
  try {
    const testDir = path.join(__dirname, '../test')
    
    // 确保 test 文件夹存在
    await fs.mkdir(testDir, { recursive: true })
    
    const downloadPromises = imageList.map(async (item) => {
      try {
        const url = item.src
        const fileName = item.name || path.basename(url).split('?')[0] || 'image'
        const fileExtension = path.extname(fileName) || '.png'
        const finalFileName = fileName.includes('.') ? fileName : `${fileName}${fileExtension}`
        const filePath = path.join(testDir, finalFileName)
        
        return new Promise((resolve, reject) => {
          const protocol = url.startsWith('https:') ? https : http
          
          protocol.get(url, (response) => {
            if (response.statusCode === 301 || response.statusCode === 302) {
              // 处理重定向
              return downloadFile(response.headers.location, filePath)
                .then(resolve)
                .catch(reject)
            }
            
            if (response.statusCode !== 200) {
              reject(new Error(`下载失败: ${response.statusCode}`))
              return
            }
            
            const fileStream = createWriteStream(filePath)
            response.pipe(fileStream)
            
            fileStream.on('finish', () => {
              fileStream.close()
              resolve({ success: true, name: item.name, path: filePath })
            })
            
            fileStream.on('error', (err) => {
              fs.unlink(filePath).catch(() => {})
              reject(err)
            })
          }).on('error', (err) => {
            reject(err)
          })
        })
      } catch (error) {
        return { success: false, name: item.name, error: error.message }
      }
    })
    
    const results = await Promise.all(downloadPromises)
    return { success: true, results }
  } catch (error) {
    return { success: false, error: error.message }
  }
})

// 辅助函数：下载文件
function downloadFile(url, filePath) {
  return new Promise((resolve, reject) => {
    const protocol = url.startsWith('https:') ? https : http
    
    protocol.get(url, (response) => {
      if (response.statusCode === 301 || response.statusCode === 302) {
        return downloadFile(response.headers.location, filePath)
          .then(resolve)
          .catch(reject)
      }
      
      if (response.statusCode !== 200) {
        reject(new Error(`下载失败: ${response.statusCode}`))
        return
      }
      
      const fileStream = createWriteStream(filePath)
      response.pipe(fileStream)
      
      fileStream.on('finish', () => {
        fileStream.close()
        resolve()
      })
      
      fileStream.on('error', (err) => {
        fs.unlink(filePath).catch(() => {})
        reject(err)
      })
    }).on('error', reject)
  })
}

